package com.woniuxy.util;

import com.baomidou.mybatisplus.extension.api.R;
import com.woniuxy.entity.dto.DictionaryDTO;
import com.woniuxy.entity.po.dic.Dictionary;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @BelongsProject: charging-management-platform
 * @BelongsPackage: com.woniuxy.util
 * @Author: Quan
 * @Date: 2025/4/1 9:47
 */
//@Component
public class RedisAboutDicUtils {
	/**
	 * 将字典中的内容放入换从中
	 * @param redisTemplate  在全局中自动封装RedisTemplate
	 * @param REDIS_KEY_CONST   传入Redis大key
	 * @param queryFunction   查询语句
	 * @return
	 * @param <T>
	 */
	public static  <T> List<?> saveAndReturnDicToRedis(
			RedisTemplate<String, Object> redisTemplate,
			String REDIS_KEY_CONST,
			Supplier<List<Dictionary>> queryFunction) {

		HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();

		// 1. 检查Redis中是否有缓存
		if (Boolean.TRUE.equals(redisTemplate.hasKey(REDIS_KEY_CONST)) && hash.size(REDIS_KEY_CONST) > 0) {
			Map<Object, Object> entries = hash.entries(REDIS_KEY_CONST);
			List<DictionaryDTO> collect = entries.entrySet().stream().map(entry -> {
				DictionaryDTO dto = new DictionaryDTO();
				dto.setId(Long.parseLong(entry.getKey().toString()));
				dto.setTypeValue(entry.getValue().toString());
				return dto;
			}).collect(Collectors.toList());
			return collect;
		}

		// 2. 如果没有缓存，则从数据库查询并转换
		List<DictionaryDTO> dictionaryDTOS = ListValueConvertUtils.listConvert(
				queryFunction,
				DictionaryDTO::new  // 这里固定使用DictionaryDTO的构造函数
		);

		// 3. 存入Redis
		dictionaryDTOS.forEach(dto -> {
			hash.put(REDIS_KEY_CONST, dto.getId().toString(), dto.getTypeValue());
		});
		redisTemplate.expire(REDIS_KEY_CONST, 20, TimeUnit.DAYS);

		return dictionaryDTOS;
	}
}